package rainy.file.synchronization.server.file;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import rainy.file.synchronization.config.RainyRunTime;

/**
 * 
 * @author dongwenbin
 *
 */
public class TailerAppender {

	private static String folder = RainyRunTime.getPropDefine("rainy.master.tail.target.folder");
	public static boolean needRolling = false;
	public static SimpleDateFormat format = new SimpleDateFormat("YY-MM-dd_HH_mm_ss");

	static {
		new TailFileRollingPolicy().start();
	}

	/**
	 * TAIL#FILENAME#CONTENT
	 * 
	 * @param commandLine
	 */
	public static void evalCommand(String commandLine) {
		if (RainyRunTime.loggerLevel.equalsIgnoreCase("debug")) {
			System.out.println(commandLine);
		}
		String[] _cl = commandLine.split(RainyRunTime.COMMAND_CONTENT_SPLIT);
		File target = new File(folder, _cl[1]);
		if (!target.exists()) {
			target.getParentFile().mkdirs();
			try {
				target.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (needRolling) {
			rollingTheFile(target);
		}
		StringBuilder strBuilder = new StringBuilder(_cl[2]);
		if (_cl.length > 3) {
			for (int i = 3; i < _cl.length; i++) {
				strBuilder.append(_cl[i]);
			}
		}
		appendToLocal(target, strBuilder.toString());
	}

	/**
	 * 以追加方式写入到最后
	 * 
	 * @param file
	 * @param line
	 */
	public static void appendToLocal(File file, String line) {
		try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
			bw.newLine();
			bw.write(line);
			bw.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * 如果日期超过固定时间则进行rolling
	 * 
	 * @param target
	 */
	private static synchronized void rollingTheFile(File target) {
		if (needRolling) {
			String pathname = target.getAbsolutePath() + "." + format.format(new Date());
			File rolledFile = new File(pathname);
			target.renameTo(rolledFile);
			try {
				target.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			needRolling = false;
		}
	}
}
